import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import UserCenter from '../views/UserCenter.vue'
import News from '../views/News.vue'
import HousePublish from '../views/HousePublish.vue'
import UserManagement from '../views/UserManagement.vue'
import HouseDetail from '../views/HouseDetail.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/house/:id',
    name: 'HouseDetail',
    component: HouseDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: UserCenter,
    meta: { requiresAuth: true }
  },
  {
    path: '/news',
    name: 'News',
    component: News,
    meta: { requiresAuth: true }
  },
  {
    path: '/house/publish',
    name: 'HousePublish',
    component: HousePublish,
    meta: { requiresAuth: true, roles: ['landlord'] }
  },
  {
    path: '/house/edit/:id',
    name: 'HouseEdit',
    component: HousePublish,
    meta: { requiresAuth: true, roles: ['landlord'] }
  },
  {
    path: '/admin/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { requiresAuth: true, roles: ['admin'] }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')

  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      // 未登录，跳转到登录页
      next({ name: 'Login' })
      return
    }

    // 需要特定角色的页面
    if (to.meta.roles && !to.meta.roles.includes(userRole)) {
      // 权限不足，跳转到首页
      next({ name: 'Home' })
      return
    }
  }

  // 已登录用户访问登录/注册页，跳转到首页
  if (token && (to.name === 'Login' || to.name === 'Register')) {
    next({ name: 'Home' })
    return
  }

  next()
})

export default router 